package cn.qqncn.furniture.service;

import cn.qqncn.furniture.mapper.OrderItemMapper;
import cn.qqncn.furniture.mapper.OrderMapper;
import cn.qqncn.furniture.pojo.domain.Order;
import cn.qqncn.furniture.pojo.domain.OrderItem;
import cn.qqncn.furniture.pojo.vo.BarVo;
import cn.qqncn.furniture.pojo.vo.CarVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 订单服务层
 */
@Service
public class OrderService {

    @Resource
    OrderMapper orderMapper;

    @Resource
    CarService carService;

    @Resource
    OrderItemMapper orderItemMapper;

    /**
     * 查找所有订单
     * @return List
     */
    public List<Order> searchAll(){
        List<Order> user1 = orderMapper.selectAll();
        return user1;
    }

    /**
     * 增加订单
     * @param userId
     * @param order
     * @return
     */
    public int addOrder(Integer userId,Order order){
        List<CarVo> carlist = carService.getCar(userId);
        UUID uuid = UUID.randomUUID();
        double sumPrice=0;
        for (int i = 0; i < carlist.size(); i++) {
            CarVo carVo = carlist.get(i);
            sumPrice+=carVo.getPrice();
        }
        order.setOrderId(uuid.toString());           //设置 订单id
        order.setUserId(userId);                     //设置  用户id
        order.setFurnitureNumber(carlist.size());    //设置 商品数量
        order.setCreateTime(new Date());             //设置 商品日期
        order.setOrderState(1);                      //设置 商品状态
        order.setOrderPrice(sumPrice);               // 设置 订单总价格
        int insert = orderMapper.insert(order);
        for (int i = 0; i < carlist.size(); i++) {
            CarVo carVo = carlist.get(i);

            // 添加到order_item表中
            OrderItem orderItem = new OrderItem();
            orderItem.setFurnitureId(carVo.getFurnitureId());
            orderItem.setFurnitureNumber(carVo.getNumber());
            orderItem.setOrderId(uuid.toString());
            orderItemMapper.insert(orderItem);
        }
        if (insert>=0)carService.deleteAllByUserId(userId);
        return insert;
    }

    /**
     * 根据用户id查询全部订单
     * @param userId
     * @return
     */
    public List<Order> selectByUserId(Integer userId){
        List<Order> orders = orderMapper.selectByUserId(userId);
        return orders;
    }

    /**
     * 查询折线图数据
     * @return
     */
    public List<BarVo> selectBar(){
        return orderMapper.selectBar();
    }
}
